package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: peterChen
 * @date: 2019/8/19 9:47
 * @description: TODO
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 从session上下文中获取已登录的用户信息
     * @return
     */
    @RequestMapping("/getUserName")
    public Result getUserName(){
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("get username error.",e);
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }

}
